package com.sky.task;

/**
 * @Classname OrderTask
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/7/7 17:24
 * @Created by Ren
 */

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类,定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {

    @Resource
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 * * * * ?") //每分钟出发一次
    //@Scheduled(cron = "0/5 * * * * ?")
    public void processTimeoutOrder(){
        //
        //LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-1);
        List<Orders> ordersList = orderMapper.processTimeoutOrder(Orders.PENDING_PAYMENT,localDateTime);
        //取消订单
        if(ordersList != null && ordersList.size() != 0 ){
            log.info("定时处理超时订单: {}", LocalDateTime.now());
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时未付款");
                orderMapper.update(orders);
            }
        }
    }

    @Scheduled(cron = "0 0 1 * * ? ") //每天凌晨一点
    //@Scheduled(cron = "0/5 * * * * ?")
    public void processDeliveryOrder(){
        //log.info("定时处理派送中订单: {}", LocalDateTime.now());
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.processTimeoutOrder(Orders.DELIVERY_IN_PROGRESS,localDateTime);
        if(ordersList != null && ordersList.size() != 0 ){
            log.info("定时处理派送中订单: {}", LocalDateTime.now());
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
